layui.use(['tree','table','layer','form','layedit', 'laydate','util'], function(){
    var tree = layui.tree;
    var table=layui.table;
    var layer=layui.layer;
    var form = layui.form;


    form.render();

var datab;
    //渲染
    tree.render({
        elem: '#test1'  ,//绑定元素
        showLine: false,
        data: getdata(),
        click: function(obj){
             datab=obj.data;
             console.log(datab);

             //根据二级分类和三级分类获取数据
            if( datab.catLevel==3||datab.catLevel==2){
                getAll(datab.catId);
            }
        }
    });

    table.render({
        elem: '#menu'
        ,width:900
        ,height:550
        ,defaultToolbar:[]
        ,toolbar:'#toolbarDemo'
        ,id:'spu'
        ,page:true
        ,cols: [[
            {type: 'checkbox'}
            ,{field:'agid', width:120, title: '分组id'}
            ,{field:'agname', width:120, title: '组名'}
            ,{field:'sort', width:120, title: '排序'}
            ,{field:'descript', width:120, title: '描述'}
            ,{field:'icon', title: '组图标', width: 120}
            ,{field:'catelogid', title: '所属分类', width: 120}
            ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:170}
        ]]
        ,data:[{
            agid:"",
            agname:"",
            sort:"",
            descript:"",
            icon:"",
            catelogid:""
        }]
    });


    //监听行工具事件
    table.on('tool(menu)', function(obj){
        var data=obj.data;
        var databack;
        //属性分组修改
        if(obj.event === 'ups'){
            //三级分类回显
            $.ajax({
               type:"post",
               url:"",
               data:{
                   catelogid:data.catelogid
               },
                dataType:"json",
                success:function (res) {
                   //要求返回格式为 "1,23,170"
                    databack=res;
                },
                error:function(res){

                }
            });
            layer.open({
                area:["700px","600px"],
                type:2,
                title:'修改',
                content:'/static/subpage/Attr_Ground/Attr_groud_edit.html',
                success:function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; // 得到iframe页的窗口对象
                    body.find('#agname').val(data.agname);
                    body.find('#sort').val(data.sort);
                    body.find('#descript').val(data.descript);
                    body.find('#icon').val(data.icon);
                    // body.find('#a').val(databack);
                    body.find('#a').val("1,23,170");
                    iframeWin.layui.form.render();
                }
            })
        }
        //关联
        else if(obj.event==='contract'){
            layer.open({
                area:["600px","600px"],
                type:2,
                title:'关联',
                content:'/static/subpage/Attr_ground/Attr_groud_contact.html'
            })
        }
        //删除
        else if(obj.event==='delete'){
            var agid=data.agid;
            $.ajax({
                type:"post",
                url:"",
                data:{
                    agid:agid
                },
                dataType:"json",
                success:function (data) {
                    if (data == 0) {
                        layer.msg('删除失败！',{icon:5,offset:"auto",time:2000});//提示框
                    }else{
                        layer.msg('删除成功！',{icon:6,offset:"auto",time:2000});//提示框
                    }
                    setTimeout(function(){
                        location.reload();//重新加载页面
                    }, 2100);
                }
            })
        }

    });

    //监听头事件
    table.on('toolbar(menu)',function(obj){
        var data=obj.data;
        if (obj.event==='csp'){
            //根据二级分类和三级分类查询
            if (datab.catLevel==3||datab.catLevel==2){
                getAll(datab.catId);
            }
        }
        //新增
        else if(obj.event==='add'){
                layer.open({
                    area:["700px","600px"],
                    type:2,
                    title:'新增',
                    content:'/static/subpage/Attr_Ground/Attr_groud_add.html'
                });
        }
        //批量删除
        else if(obj.event==='pdelete'){
            layer.confirm('确定要删除吗？',function (index) {
            var checkStatus = table.checkStatus('spu')
                ,checkData = checkStatus.data,
                delList=[];
            for (var i = 0; i < checkData.length; i++) {
                delList.push(checkData[i].agid);
            }
            //json对象
            var strify = JSON.stringify(delList);
            console.log(delList);
            console.log(strify);
            $.ajax({
                url:"",
                dataType:'json',
                data:{
                    datas:strify
                },
                type:'post',
                success:function(data){
                    if (data == 0) {
                        layer.msg('删除失败！',{icon:5,offset:"auto",time:2000});//提示框
                    }else{
                        layer.msg('删除成功！',{icon:6,offset:"auto",time:2000});//提示框
                    }

                    setTimeout(function(){
                        location.reload();//重新加载页面表格
                    }, 2100);
                }
            });
            // return false;
            });
        }

    });
    //根据查询条件查询
    function getAll(d){
        // var keyname=$("#keyname").find("option:selected").text();
        var key=$("#key").val();


        // console.log(key);
        table.reload('spu',{
            method:"get",
            url:"/product/pmsspu/spuc",
            where:{
                cid:d,
                key:key
            }
        });
    }


    //tree 改变字段title->name
    function getdata(){
        var data=[];
        $.ajax({
            url:'/product/pmscategory/list/tree',
            type:'get',
            async:false,
            success:function(databack){
              let kd=changeTreeDate(databack, 'title', 'name');
                data=kd;
            }

        });
        return data.data;
    }





    /**
     * 修改json数据key名称的方法
     * params date <array> 需要修改的json格式的数组
     * params newKey <string> 需要修改成的key值
     * params oldKey <string> 需要被修改的key值
     */
    function changeTreeDate(zf_jsonObj, newKey, oldKey) {
        let str = JSON.stringify(zf_jsonObj);
        let reg = new RegExp(oldKey, 'g');
        let newStr = str.replace(reg, newKey);
        return JSON.parse(newStr);
    }








});








